/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vanniktech.vntnumberpickerpreference;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

/**
 * Preference工具类
 *
 * @since 2021-05-24
 */
public class PreferenceUtils {
    private static PreferenceUtils instance = null;

    private PreferenceUtils() {
    }

    /**
     * 静态锁对象
     *
     * @return Utils
     */
    public static synchronized PreferenceUtils getInstance() {
        if (instance == null) {
            instance = new PreferenceUtils();
        }
        return instance;
    }

    /**
     * 存放key和value
     *
     * @param context 上下文
     * @param key key值
     * @param value value值
     */
    public static void putString(Context context, String key, String value) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        Preferences preferences = databaseHelper.getPreferences(Constants.SPKEYNAME);
        preferences.putString(key, value);
        preferences.flushSync();
    }

    /**
     * 根据key获取value
     *
     * @param context 上下文
     * @param key key值
     * @param value value值
     * @return String获取的String
     */
    public static String getString(Context context, String key, String value) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        Preferences preferences = databaseHelper.getPreferences(Constants.SPKEYNAME);
        return preferences.getString(key, value);
    }

    /**
     * 根据key获取value
     *
     * @param context 上下文
     * @param key key值
     */
    public static void deleteString(Context context, String key) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        Preferences preferences = databaseHelper.getPreferences(Constants.SPKEYNAME);
        preferences.delete(key);
    }
}
